import './presetVar'
import React, { Component } from 'react';
import { createPage, base, toast, pageTo } from 'nc-lightapp-front';
import { tableButtonClick, pageButtonClick, beforeEvent,afterEvent, pageInfoClick, refreshButtonClick } from './events';
import initTemplate from './initTemplate';
import {getCookie, dataHandle, viewInitBil,routeChange} from './initTemplate'
// import Uploader from 'ssccommon/components/uploader'
import {getAfterEventParams} from 'ssccommon/utils/formulaUtils'
import pubMessage from 'ssccommon/utils/pubMessage'
import getAttachmentLength from '../../../public/components/linkAttachment/getAttachmentLength'
import ApproveDetail from 'uap/common/components/ApproveDetail';
import requestApi from "./requestApi"; 
import attachments from 'uap/common/components/getAttachmentInfo';
import LoanDetail from '../../loandetail/card';

const { getAttachments, getAttachmentsInfo } = attachments;
let {NCModal} = base;
import {
    BillStyle,
    BillHead,
    BillBody,
    Form,
    CardTable,
    CardTableGroup,
    ButtonGroup,
    MultiButtonGroup
} from 'ssccommon/components/bill';

import './index.less';
import LinkQueryJkbxModel from 'ssccommon/linkquery/LinkQueryJkbxModel';
import Inspection from 'epmp/exports/components/Inspection';
import NCUploader from 'uap/common/components/NCUploader';
import ApprovalTrans from 'uap/common/components/approvalTrans';

const pageButton = window.presetVar.pageButton;

window.assingUsers=[]//指派信息
window.sureAssign = false;//确定指派
window.assignBillId = '';//有指派的情况下，第一次点保存提交实际保存成功的单据pk

class jkbxBillCard extends Component {
    constructor(props) {
        super(props);
        this.dataSource = 'erm.expenseaccount.initbills.config';
        this.cardPagStatus = {
            modify: 1,
            add: 2,
            del: 3
        }
        this.state = {
            target: null,
            showUploader: false,
            modalControl: false,
            fileList:[],
            groupLists:0,
            billId : '',
            showLinkQueryFysqModel: false,
            showLinkQueryJkbxModel: false,
            sourceData: null,
            showLinkBudget: false,
            isinit : props.getUrlParam("isinit"),
	        hideTables:[],
            showBack : false,
            ShowApproveDetail: false,
            billtype: '',
            pageInfoShow : false,
            compositedata : '',
            compositedisplay : '',
            transtype_name:'',
            linkData : '',
            uploaderBtnDisable: false, //附件上传按钮可用状态
            showLoanDetailModel: false, //联查借款单详情
        }
        //initTemplate.call(this, props);
        this.pubMessage = new pubMessage(props);
        if(props.getUrlParam("isinit") === 'true'){
	        if(props.getUrlParam("status") === 'browse'){
                this.setState({ pageInfoShow : true });
            }
            window.setTimeout(() => {
                this.setState({ showBack : true})
            }, 20);
        }
        
        let billid=props.getUrlParam("id")
        if(billid){
        getAttachmentLength(billid).then(lists=>{
        
            this.setState({
                groupLists:lists
            },()=>{
            initTemplate.call(this, props, true);
            })
        })
        }else{
            initTemplate.call(this, props);
        }

        // TOP NCCLOUD-61317 增加公式编辑后联动 chengwebc ADD
        props.setRelationAfterEventCallBack && props.setRelationAfterEventCallBack((props, changedField, changedArea, oldCard, newCard, index, rowId)=>{
            let params = getAfterEventParams(props, changedField, changedArea, oldCard, newCard, index, rowId);
            params.map((one)=>{
                afterEvent.call(this, props, one.moduleId, one.key, one.value, one.changedrows, one.index)
            })
        });
        // BTM NCCLOUD-61317 增加公式编辑后联动 chengwebc

        props.use.form('head');
    }

    componentWillMount() {
                   window.onbeforeunload = () => {
                    let status = this.props.getUrlParam("status");
                    let addType = this.props.getUrlParam('addType');
                    if (addType!="pull" && (status == 'edit'||status == 'add')) {
                        return '当前单据未保存，确认离开？'/* 国际化处理： 确定要离开吗？*/
                    }
                }
            }

    // //删除单据
    // billRemove(){
        
    // }
    // billInvalid(){
    //     // let param = {};
    //     // param.pagecode=this.props.getSearchParam("p");
    //     // param.openbillid=this.props.getUrlParam("id");
    //     // param.tradetype=window.presetVar.tradetype;
    //     // requestApi.billInvalid({
    //     //     data: param,
    //     //     success: (data) => {
    //     //         location.reload();
    //     //         if (data.success) {
    //     //             location.reload();
    //     //         }
    //     //     }
    //     // });
    // }
    componentDidMount(props) {
        this.props.setHashChangeCallback(() => {
            routeChange.call(this, this.props);
        })
    }

    componentDidUpdate(){

    }
    cancel(){
        this.setState({
            showLinkBudget: false
        })
    }
    affirm(info){
        this.setState({
            showLinkBudget: false
        })
    }
    closeApprove = () => {
        this.setState({
            ShowApproveDetail: false
        })
    }
    getAssginUser = (value) => {
        window.assingUsers = value;
        window.sureAssign = true;
        pageButtonClick.call(this)[pageButton.billSubmit]();
        window.assignBillId = '';
    }

    turnOff(){
        this.setState({
            compositedisplay:false
        }) ;
        window.sureAssign = false;
        window.assingUsers = [];
        let props = this.props;
        let billid = window.assignBillId;
        if(!billid){
            billid = props.form.getFormItemsValue("head","pk_jkbx").value;
        }
        window.presetVar.redata = 'Y';
        pageTo.specialLinkTo('/erm/expenseaccount/loanmanage/card/index.html',{scene:props.getUrlParam('scene'),pagecode:props.getSearchParam('p'),isfromSsc:true,status:window.presetVar.status.browse,id:billid,tradetype:window.presetVar.tradetype, ntbCheck:'false'});
        routeChange.call(this, this.props)
    }

    renderErrorCenterState () {
        const { props } = this
        const { socket } = props;
        const status = props.form.getFormItemsValue('head', 'saga_status')
        if (!status || status.value !== '1') return null;
        
        this.props.button.toggleErrorStatus('head',{
            isError: true
        })

        const param = {
            headBtnAreaCode: 'head',
            formAreaCode: 'head',
            billtype: props.form.getFormItemsValue('head', 'saga_status').value,
            billpkname: 'pk_jkbx',
            dataSource: 'erm.expenseaccount.loanmanage.card'
        }
        return props.socket.connectMesg(param)
    }

    render() {
        let {modal, cardPagination } = this.props;
        let { target } = this.state
        let {createModal} = modal;
        const { createCardPagination } = cardPagination;

        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
        let btnModalConfig = {
            [pageButton.pageDel]: {
                // "2011-0004": "删除"
                // "2011-0005": "确认删除该单据吗？"
                title: multiLang && multiLang.get('2011-0004'),
                content: multiLang && multiLang.get('2011-0005'),
            },
            [pageButton.billInvalid]: {
                // "2011-0009": "作废",
                // "2011-0010": "确认作废该单据吗？"
                title: multiLang && multiLang.get('2011-0009'),
                content: multiLang && multiLang.get('2011-0010'),
            }
        }
        return (
            <div >
                {this.renderErrorCenterState()}
            <BillStyle
                {...this.props}
            >
            <BillHead 
                back={{
                    showBack : this.state.showBack,
                    onClick : () =>{
                        this.props.pushTo('/list',{
                            appcode:'201103QCDJ',
                            pagecode:'201103QCDJ_list'
                        });
                    }
                }}
                title={this.state.transtype_name}
                refreshButtonEvent={refreshButtonClick.bind(this)}
	    	    pageInfoConfig={{
                    show:this.state.pageInfoShow,
                    handlePageInfoChange: pageInfoClick.bind(this),
                    dataSource : this.dataSource
                }} >
                <ButtonGroup
                    areaId="head"
                    buttonEvent={pageButtonClick.bind(this)}
                    modalConfig={btnModalConfig}
                    sagasButtonVisible={true}
                />
                <Form
                areaId="head"
                onAfterEvent={afterEvent.bind(this)}/>
            </BillHead>

            <BillBody>


                    <CardTableGroup
                        excludeTableAreaId={null}
                        totalItemCode="amount"
                        totalItemCodeByAreas={ //
                            {
                                'accrued_verify': 'verify_amount',
                                'er_bxcontrast':'cjkybje',
                                'er_cshare_detail':'assume_amount'
                            }
                        }
                        modelSave={pageButtonClick.call(this)['pageSave']}
                        //侧拉删除事件,2012版本接口变化,通过回调事件自行调用
                        modelDelRowBefore={(scope, moduleId, index, record) => {
                            if((record.status == 1 || record.status == 0) && record.values.pk_mtapp_detail&& record.values.pk_mtapp_detail.value) {
                                // '由申请生成的借款明细不允许删除,请知悉!'
                                toast({content: multiLang && multiLang.get('201107TZD-0003'), color:'danger'})
                                return false
                            }
                            // return true
                            this.props.cardTable.delRowsByIndex(moduleId, index)
                        }}
                        onBeforeEvent={beforeEvent.bind(this)}
                        onAfterEvent={afterEvent.bind(this)}
                        invisibleTables={this.state.hideTables}
                    >
                    <MultiButtonGroup buttonEvent={tableButtonClick(window._tableButtonsClick).bind(this)}   />
                </CardTableGroup>

                {
                    this.state.showUploader && 
                    < NCUploader
                        disableButton={ this.state.uploaderBtnDisable }
                        billId={ this.state.billId }
                        target={target}
                        onHide={() => {
                            this.setState({showUploader: false})
                            getAttachmentLength(this.state.billId).then(lists => {
                                //附件
                                this.props.button.setButtonTitle('fileManager', multiLang && multiLang.get('201102JCLF_C-0013') + ' ' + lists + ' ');
                            })}
                        }
                        customize={{'pk_billtypecode':this.props.getUrlParam('tradetype'), "djdl":"jk"}}
                        customInterface={
                            {
                                queryLeftTree:"/nccloud/erm/pub/ErmAttachmentTreeNodeQueryAction.do",
                                queryAttachments: "/nccloud/erm/pub/ErmAttachmentQueryAction.do"
                            }
                        }

                        placement={'bottom'} 
                    />
                }

                <div>
                    {<ApproveDetail
                        show={this.state.ShowApproveDetail}
                        close={this.closeApprove}
                        billtype={this.state.billtype}
                        billid={this.state.billId}
                    />}
                </div>

               
            </BillBody>

            </BillStyle>
                {/* {this.state.modalControl&&
                <Uploader
                    {...this.props}
                    modalControl={() => {
                        this.setState({
                            modalControl: false
                        })
                    }}
                    // 标题
                    //"201102BCLF-0001": "电子发票上传列表"
                    title={multiLang && multiLang.get('201102BCLF-0001')}
                    // title="电子发票上传列表"
                    // 上传文件列表
                    fileList={this.state.fileList}
                    // 附件上传限制
                    attachMaxSize={'3'}

                    billId = {this.state.billId}
                    // 上传附件接口
                    uploadAttachment={'/nccloud/erm/expenseaccount/ExpenseaccountDzfp.do'}
                    // 列表模板
                    listTemplate={getInvoiceTpl.call(this)}

                    uploadChange={invoiceEvent.done.bind(this)}
                />
                } */}

               {/* 查看借款情况 */}
                {
                    this.state.showLoanDetailModel ?
                    <NCModal 
                        size="xlg" 
                        show = { this.state.showLoanDetailModel }
                        onHide = { () => this.setState({showLoanDetailModel: false})}
                    >
                        <NCModal.Header closeButton="true">
                                {/*"201107TZD-0002": "借款情况",*/}
                                <NCModal.Title >{multiLang && multiLang.get('201107TZD-0002')}</NCModal.Title>
                        </NCModal.Header>
                        <NCModal.Body>
                                <LoanDetail  showLoanDetailModel={this.state.showLoanDetailModel}  />
                        </NCModal.Body>
                    </NCModal>
                    : null
                }

                {/* 联查费用申请单 */}
                {/*<LinkQueryFysqModel
                    show={this.state.showLinkQueryFysqModel} 
                    close={() => this.setState({showLinkQueryFysqModel: false})} 
                    tradetype={window.presetVar.tradetype}
                    openBillId={this.state.billId}
                    {...this.props} />*/}

               
                {/* 联查报销单 */}
                <LinkQueryJkbxModel
                    show={this.state.showLinkQueryJkbxModel} 
                    linkData={this.state.linkData}
                    close={() => this.setState({showLinkQueryJkbxModel: false})} 
                    tradetype={window.presetVar.tradetype}
                    openBillId={this.state.billId}
                    {...this.props} />
                <div>
                    <Inspection
                        show={ this.state.showLinkBudget }
                        sourceData = { this.state.sourceData }
                        cancel = { this.cancel.bind(this) }
                        affirm = { this.affirm.bind(this) }
                    />
                </div>
                <div>
                    {/*"201102FYYT-0003": "指派",*/}
                    {this.state.compositedisplay ? <ApprovalTrans
                        title= {multiLang && multiLang.get('201102FYYT-0003')}
                        data={this.state.compositedata}
                        display={this.state.compositedisplay}
                        getResult={this.getAssginUser}
                        cancel={this.turnOff.bind(this)}
                     /> : ""}
                </div>
            </div>
        )
    }
}

jkbxBillCard = createPage({
    mutiLangCode: '2011',
    billinfo:{
        billtype: 'extcard', 
        pagecode: pageTo.getSearchParam("p"), 
        headcode: 'head',
        bodycode: ['jk_busitem', 'er_bxcontrast']
    },
    orderOfHotKey: ['jk_busitem']
})(jkbxBillCard);

export default jkbxBillCard;